package mobileann.mafamily.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mobileann.mafamily.act.main.FS;
import mobileann.mafamily.act.main.LoginRegActivity;
import mobileann.mafamily.act.member.AddByAcountActivity;
import mobileann.mafamily.act.member.CaptureActivity;
import mobileann.mafamily.act.member.MemberInfoActivity;
import mobileann.mafamily.act.setup.MyCenterActivityNew;
import mobileann.mafamily.adapter.MemberSpinnerAdapter;
import mobileann.mafamily.db.model.MembersModel;
import mobileann.mafamily.db.model.UserModel;
import mobileann.mafamily.entity.MemberInfoEntity;
import mobileann.mafamily.entity.UserInfoEntity;
import mobileann.mafamily.model.UDPSocket;
import mobileann.mafamily.service.MainService;
import mobileann.mafamily.utils.code.CodeUtils;
import mobileann.mafamily.widgets.CircleView;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.mobileann.mafamily.R;
import com.mofind.android.base.L;
import com.mofind.android.net.HttpUtils;
import com.mofind.android.net.JSONParser;

public class MemberListUtils {
	public static final int MAIN_EYE = 10;
	public static final int ACT_LOCK = 11;
	public static final int ACT_HISTIME = 12;
	public static final int MEMBER_CHANGER = 13;
	public static final int MAP_ALLMEMBER_LOCATION = 14;

	public static final int GET_MEMBERS = 360;
	public static final int GET_MEMBERS_ERROR = 361;

	private UserInfoEntity currentUser;
	private UserInfoEntity mySelf;
	private List<UserInfoEntity> members;
	private List<UserInfoEntity> nowMembers;
	private List<UserInfoEntity> babyMembers;
	private Map<String, String> locMap;

	private MemberListUtils() {
		// this.currentUser = FS.getInstance().self();
		// this.members = FS.getInstance().mMemberAll;
		setMembers(FS.getInstance().mMemberAll);
		//		setCurrentUser(FS.getInstance().self());
		nowMembers = new ArrayList<UserInfoEntity>();
		babyMembers = new ArrayList<UserInfoEntity>();
		locMap = new HashMap<String, String>();
	}

	private static MemberListUtils instance;

	public synchronized static MemberListUtils getInstance() {
		if (instance == null) {
			instance = new MemberListUtils();
		}
		return instance;
	}

	public Map<String, String> getLocMap(){
		return locMap;
	}
	public void setMySelf(){

	}

	public UserInfoEntity getMySelf(){
		for (UserInfoEntity u : members) {
			if (!u.getUid().equals(SPUtils.getUID())) {
				mySelf = u;
			}
		}
		return mySelf;
	}

	public void setCurrentUser(UserInfoEntity user) {
		this.currentUser = user;
	}

	public void setCurrentUser(String uid) {
		for(UserInfoEntity user : members){
			if(user.getUid().equals(uid)){
				this.currentUser = user;
			}
		}
	}

	public UserInfoEntity getCurrentUser() {
		if (currentUser == null) {
			this.currentUser = new UserInfoEntity();
			this.currentUser.setFid(SPUtils.getFID());
			this.currentUser.setUid(SPUtils.getUID());
			this.currentUser.setRole(SPUtils.getRole());
			this.currentUser.setNickname(SPUtils.getNickName());
		}
		return currentUser;
	}

	public void setMembers(List<UserInfoEntity> list) {
		this.members = list;
	}

	public List<UserInfoEntity> getMembers() {
		return members;
	}

	public List<UserInfoEntity> getNowMembers() {
		nowMembers.clear();
		for (UserInfoEntity u : members) {
			if (!u.getUid().equals(currentUser.getUid())) {
				nowMembers.add(u);
			}
		}
		return nowMembers;
	}

	public List<UserInfoEntity> getBabyMembers() {
		babyMembers.clear();
		for (UserInfoEntity u : members) {
			if (!u.getUid().equals(currentUser.getUid()) && u.getRole() == 2) {
				babyMembers.add(u);
			}
		}
		return babyMembers;
	}

	public List<UserInfoEntity> getMyMembers() {
		List<UserInfoEntity> mine = new ArrayList<UserInfoEntity>();
		for (UserInfoEntity u : members) {
			if (!u.getUid().equals(FS.getInstance().self().getUid())) {
				mine.add(u);
			}
		}
		return mine;
	}

	/**
	 * 主要功能：
	 * <br>在主界面中显示家庭所有成员的图片和列表
	 * @param c  显示的上下文 
	 * @param l  要显示的布局
	 * @param tag  
	 * @param arrow  ImageView的显示
	 * @param handler 回传消息的handler
	 * @annotation ADRIAN.2015.7.28.12.27
	 */
	public void showList(final Context c, LinearLayout l, final int tag,
			final ImageView arrow, final Handler handler) {
		if (FS.getInstance().self().getRole() == 2) {
			setCurrentUser(FS.getInstance().self());
			return;
		}
		View popupLayout = LayoutInflater.from(c).inflate(R.layout.popview_member_list, null);
		ListView list = (ListView) popupLayout.findViewById(R.id.memberList);
		LinearLayout iv = (LinearLayout) popupLayout.findViewById(R.id.moreMemberIv);
		FrameLayout map_allmember = (FrameLayout) popupLayout.findViewById(R.id.map_allmember);
		map_allmember.setVisibility(View.GONE);
		final PopupWindow pop = new PopupWindow(popupLayout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		pop.setWidth((int) c.getResources().getDimension(R.dimen.mainmap_spinner_width));
		pop.setBackgroundDrawable(new BitmapDrawable(c.getResources(), (Bitmap) null));
		pop.setHeight(LayoutParams.WRAP_CONTENT);
		pop.setOutsideTouchable(true);
		pop.setFocusable(true);
		doRotateAnimation(c,arrow,1);
		pop.showAtLocation(l, Gravity.LEFT | Gravity.TOP, (int) c
				.getResources().getDimension(R.dimen.hor_spacing16), (int) c
				.getResources().getDimension(R.dimen.ver_spacing160));
		pop.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				doRotateAnimation(c, arrow, 2);
			}
		});
		if (getMembers().size() <= 1) {
			list.setVisibility(View.GONE);
			iv.setVisibility(View.VISIBLE);
			CircleView headCircle = (CircleView) popupLayout.findViewById(R.id.headCircle);
			headCircle.setBackColor(0x2E000000);
			iv.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (pop != null) {
						pop.dismiss();
					}
					Intent intent = new Intent(c, CaptureActivity.class);
					c.startActivity(intent);
				}
			});
		} else {
			list.setVisibility(View.VISIBLE);
			iv.setVisibility(View.GONE);
			List<UserInfoEntity> memberlist = new ArrayList<UserInfoEntity>();
			if (tag == ACT_LOCK) {
				memberlist = getBabyMembers();
			} else {
				memberlist = getNowMembers();
			}

			final MemberSpinnerAdapter adapter = new MemberSpinnerAdapter(c, memberlist);
			list.setAdapter(adapter);
			list.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {
					if (pop != null) {
						pop.dismiss();
					}
					UserInfoEntity user = adapter.getItem(position);
					setCurrentUser(user);
					handler.obtainMessage(MEMBER_CHANGER).sendToTarget();
					// switch(tag){
					// case MAIN_EYE:
					// break;
					// case ACT_LOCK:
					// break;
					// case ACT_HISTIME:
					// break;
					// default:
					// break;
					// }
				}
			});
		}
	}

	private void doRotateAnimation(final Context c,final ImageView v,final int tag){
		RotateAnimation Rotate;
		if(tag == 1){
			Rotate = new RotateAnimation(0f, -180f,
					Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		}else{
			Rotate = new RotateAnimation(0f, 180f,
					Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		}
		Rotate.setDuration(500);
		v.setAnimation(Rotate);
		v.startAnimation(Rotate);
		Rotate.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				v.clearAnimation();
				if(tag == 1)
					setRotate(c, v);
				else
					v.setImageResource(R.drawable.user_info_arrow);
			}
		});
	}

	private void setRotate(Context c,ImageView v){
		final Bitmap bitmap=BitmapFactory.decodeResource(c.getResources(), R.drawable.user_info_arrow);
		v.setImageBitmap(bitmap);
		//创建操作图片是用的matrix对象
		Matrix matrix=new Matrix();
		//缩放图片动作
		matrix.postScale(1, 1);
		//旋转图片动作
		matrix.postRotate(-180);// 旋转30°
		//创建新图片
		Bitmap resizedBitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
		//将上面创建的bitmap转换成drawable对象，使其可以使用在ImageView,ImageButton中
		BitmapDrawable bmd=new BitmapDrawable(resizedBitmap);
		v.setAdjustViewBounds(true);
		v.setImageDrawable(bmd);
	}

	public void requestStatus(String uid) {
		UDPSocket.getInstance(FS.getInstance()).sendGetUserStateRequest(
				FS.getInstance().self().getUid(), uid);
		UDPSocket.getInstance(FS.getInstance()).sendGetUserTopAppRequest(
				FS.getInstance().self().getUid(), uid);
	}

	/** 功能:当进入APP的时候, 通知每个人我在线  @ADRIAN.2015.99 */
	public void requestStatusToNotifyEveryOnline(String uid) {
		UDPSocket.getInstance(FS.getInstance()).sendGetUserTopAppRequest(
				FS.getInstance().self().getUid(), uid);
	}

	public void goMemberInfo(Context c) {
		if (currentUser != null && FS.getLoginState()) {
			if (currentUser.getUid().equals(FS.getInstance().self().getUid())) {
				Intent intent3 = new Intent(c, MyCenterActivityNew.class);
				//				Intent intent3 = new Intent(c, MyCenterActivity.class);
				c.startActivity(intent3);
			} else {
				Intent intent3 = new Intent(c, MemberInfoActivity.class);
				intent3.putExtra("member", currentUser);
				c.startActivity(intent3);
			}
		} else {
			//			Intent intent3 = new Intent(c, LoginActivity.class);
			Intent intent3 = new Intent(c, LoginRegActivity.class);
			c.startActivity(intent3);
		}
	}


	/**
	 * 主要功能: 显示所有家庭成员的列表
	 * 所用地:
	 * <br> 1. 位置界面
	 * @param c
	 * @param l
	 * @param handler
	 * @param memberLists
	 * @annotation ADRIAN.2015.8.14.11.08
	 */
	public void showMapMemberList(final Context c, LinearLayout l, final Handler handler,
			List<UserInfoEntity> memberLists) {
		View popupLayout = LayoutInflater.from(c).inflate(R.layout.popview_member_list, null);
		ListView list = (ListView) popupLayout.findViewById(R.id.memberList);
		LinearLayout iv = (LinearLayout) popupLayout.findViewById(R.id.moreMemberIv);
		View footerView=LayoutInflater.from(c).inflate(R.layout.mapmember_footview, null);
		list.addFooterView(footerView);
		final FrameLayout map_allmember = (FrameLayout) footerView.findViewById(R.id.map_allmember);
		final PopupWindow pop = new PopupWindow(popupLayout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		pop.setWidth((int) c.getResources().getDimension(R.dimen.mainmap_spinner_width));
		pop.setBackgroundDrawable(new BitmapDrawable(c.getResources(), (Bitmap) null));
		pop.setHeight(LayoutParams.WRAP_CONTENT);
		pop.setOutsideTouchable(true);
		pop.setFocusable(true);
		pop.showAtLocation(l, Gravity.LEFT | Gravity.BOTTOM,
				(int) c.getResources().getDimension(R.dimen.hor_spacing16),
				(int) c.getResources().getDimension(R.dimen.ver_spacing72));
		if (getMembers().size() <= 1) {
			list.setVisibility(View.GONE);
			//			map_allmember.setVisibility(View.GONE);
			iv.setVisibility(View.VISIBLE);
			CircleView headCircle = (CircleView) popupLayout.findViewById(R.id.headCircle);
			headCircle.setBackColor(0x2E000000);
			iv.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (pop != null) {
						pop.dismiss();
					}
					Intent intent = new Intent(c, CaptureActivity.class);
					c.startActivity(intent);
				}
			});
		} else {
			final MemberSpinnerAdapter adapter = new MemberSpinnerAdapter(c, memberLists);
			list.setVisibility(View.VISIBLE);
			list.setAdapter(adapter);
			//			map_allmember.setVisibility(View.VISIBLE);
			map_allmember.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					handler.obtainMessage(MAP_ALLMEMBER_LOCATION).sendToTarget();
					pop.dismiss();
				}
			});
			iv.setVisibility(View.GONE);
			list.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {
					if (pop != null) {
						pop.dismiss();
					}
					UserInfoEntity user = adapter.getItem(position);
					MemberListUtils.getInstance().setCurrentUser(user);
					handler.obtainMessage(MEMBER_CHANGER).sendToTarget();
				}
			});
		}
	}

	public void showAddMember(final Context c, FrameLayout rightBtn){
		View popupView = LayoutInflater.from(c).inflate(R.layout.popview_addmember, null);
		final PopupWindow mPopupWindow = new PopupWindow(popupView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		mPopupWindow.setTouchable(true);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setWidth(UIUtils.currentScreenX() / 2);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable(c.getResources(), (Bitmap) null));
		mPopupWindow.showAtLocation(rightBtn,
				Gravity.RIGHT | Gravity.TOP,
				(int) c.getResources().getDimension(R.dimen.hor_spacing8),
				(int) c.getResources().getDimension(R.dimen.oldaddmember_verspacing));
		//===================================================================
		LinearLayout addmember_popview_scanner = (LinearLayout) popupView
				.findViewById(R.id.addmember_popview_scanner);
		addmember_popview_scanner.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(c, CaptureActivity.class);
				c.startActivity(intent);
				if (mPopupWindow != null)
					mPopupWindow.dismiss();
				MySelfUtils.getInstance().getTagClick(c, 110700);
			}
		});
		//====================================================================
		LinearLayout addmember_popview_byacount = (LinearLayout) popupView
				.findViewById(R.id.addmember_popview_byacount);
		addmember_popview_byacount.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(c, AddByAcountActivity.class);
				c.startActivity(intent);
				if (mPopupWindow != null)
					mPopupWindow.dismiss();
				MySelfUtils.getInstance().getTagClick(c, 110700);
			}
		});
		//=================================================================
		LinearLayout addmember_popview_code = (LinearLayout) popupView
				.findViewById(R.id.addmember_popview_code);
		addmember_popview_code.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				View codeView = LayoutInflater.from(c).inflate(R.layout.dlg_mycode, null);
				ImageView imageView = (ImageView) codeView.findViewById(R.id.iv_dl_qrcode);
				try {
					imageView.setImageBitmap(CodeUtils.getInstance(c).qr_code(BarcodeFormat.QR_CODE));
				} catch (WriterException e) {
					L.e("maf", "error--", e);
				}
				ImageView iv_mycode_headericon = (ImageView) codeView.findViewById(R.id.iv_mycode_headericon);
				FS.getInstance().loadIcon(c, iv_mycode_headericon, FS.getInstance().self().getUid(), 1);
				TextView tv_mycode_nickname = (TextView) codeView.findViewById(R.id.tv_mycode_nickname);
				tv_mycode_nickname.setText(FS.getInstance().self().getNickname());
				TextView tv_mycode_uid = (TextView) codeView.findViewById(R.id.tv_mycode_uid);
				tv_mycode_uid.setText(FS.getInstance().self().getUid());
				AlertDialog dialog = new AlertDialog.Builder(c).setView(codeView).show();
				if (mPopupWindow != null)
					mPopupWindow.dismiss();
			}
		});
	}

	/**
	 * 判断此UID是否是家庭成员里面的
	 * @param aUid
	 * @return
	 */
	public boolean isAFamily(String aUid){
		boolean isAFamily = false;
		if(!members.isEmpty() && members != null){
			for (int i = 0, count = members.size(); i < count/*members.size()*/; i++) {
				if (members.get(i).getUid().equals(aUid)
						&& !FS.getInstance().self().getUid().equals(aUid)) {
					isAFamily = true;
				}
			}
		}
		return isAFamily;
	}

	public String getName(String uid){
		String name = "";
		if(!members.isEmpty() && members != null){
			for(UserInfoEntity user : members){
				if(user.getUid().equals(uid)){
					name = user.getNickname();
				}
			}
		}
		return name;
	}

	public int getRole(String uid){
		int role = 4;
		if(!members.isEmpty() && members != null){
			for(UserInfoEntity user : members){
				if(user.getUid().equals(uid)){
					role = user.getRole();
				}
			}
		}
		return role;
	}

	//==========================================================
	private String getMembersQuertStr() {
		// String queryStr = SPUtils.getFID2() + "_" + SPUtils.getFRAD()
		// + "_member";
		//		String queryStr = SPUtils.getMySelf(SPUtils.MYFID) + "_"
		//				+ SPUtils.getMySelf(SPUtils.MYFRAD) + "_member";
		return new StringBuilder(256).append(SPUtils.getMySelf(SPUtils.MYFID)).append("_")
				.append(SPUtils.getMySelf(SPUtils.MYFRAD)).append("_member").toString();
		//		return queryStr;
	}

	/**
	 * 功能:获取所有家庭成员的信息
	 * @param context
	 * @param handler
	 * @annotation ADRIAN.2015.99
	 */
	public void getMembersUID(final Context context, final Handler handler) {
		HttpUtils.startHttpGet(URLUtils.URL_TASK_GET + getMembersQuertStr(),
				new HttpUtils.HttpResultCallback() {

			@Override
			public void result(String url, boolean isResult, String jsonStr) {
				if (isResult) {
					try {
						// String json = TripleDESUtil.getJsonArrStr(
						// SPUtils.getFID2(), SPUtils.getFRAD(),
						// jsonStr);
						String json = TripleDESUtil.getJsonArrStr(
								SPUtils.getMySelf(SPUtils.MYFID),
								SPUtils.getMySelf(SPUtils.MYFRAD), jsonStr);
						if (TextUtils.isEmpty(json)) {
							if (handler != null)
								handler.obtainMessage(GET_MEMBERS_ERROR).sendToTarget();
						} else if (json.startsWith("{\"")) {
							if (handler != null)
								handler.obtainMessage(GET_MEMBERS_ERROR).sendToTarget();
						} else {
							JSONArray ja = JSONParser.getJSONArray(json);
							if (ja.length() == 0) {
								if (handler != null)
									handler.obtainMessage(GET_MEMBERS_ERROR).sendToTarget();
							} else {
								// MembersModel.delMembersTab(context);
								List<UserInfoEntity> members = new ArrayList<UserInfoEntity>();
								for (int i = 0; i < ja.length(); i++) {
									JSONObject jo = ja.getJSONObject(i);
									String uid = JSONParser.getString(jo, "uid");
									String name = JSONParser.getString(jo, "name");
									String phone = JSONParser.getString(jo, "phone");
									String role = JSONParser.getString(jo, "role");
									String urad = JSONParser.getString(jo, "urad");
									String avatar = JSONParser.getString(jo, "avatar");
									MemberInfoEntity memberInfo = new MemberInfoEntity(
											uid, urad, name, role, phone, avatar);
									UserInfoEntity userInfoEntity = new UserInfoEntity();
									// userInfoEntity.setUid(uid);
									userInfoEntity.setUid(phone);
									userInfoEntity.setNickname(name);
									userInfoEntity.setIcon(avatar);
									userInfoEntity.setRole(Integer.parseInt(role));
									userInfoEntity.setTelephone(phone);
									userInfoEntity.setFid(SPUtils.getMySelf(SPUtils.MYFID));
									members.add(userInfoEntity);
									MembersModel.insertMembers(context,	memberInfo);
									// 异步下载图片
									if (!("").equals(phone)	&& !("").equals(avatar) 
											&& phone != null && avatar != null) {
										IconImageUtils.getInstance().downIconImgIfNotExits(phone,avatar);
									}
								}
								FS.getInstance().mMemberAll = members;
								UserModel userModel = new UserModel(FS.getInstance());
								userModel.deleteUserInfoTable();
								userModel.insertMemberAll(FS.getInstance().mMemberAll);// 保存成员信息到数据库
								FS.getInstance().updateDBData();
								/* 代码逻辑与框架结构很重要 */
								MemberListUtils.getInstance()
								.setMembers(members);
								if (handler != null)
									handler.obtainMessage(GET_MEMBERS,	members).sendToTarget();
							}
						}
					} catch (Exception e) {
						L.e("maf", "error--", e);
					}

				}
			}
		});
	}

	/**
	 * 功能:获取所有家庭成员的信息, 主要是为了第一次进入界面, 通知所有用户'我'在线
	 * @param context
	 * @param handler
	 * @annotation ADRIAN.2015.99
	 */
	public void getMembersUID4Online(final Context context, final Handler handler) {
		HttpUtils.startHttpGet(URLUtils.URL_TASK_GET + getMembersQuertStr(),
				new HttpUtils.HttpResultCallback() {

			@Override
			public void result(String url, boolean isResult, String jsonStr) {
				if (isResult) {
					try {
						String json = TripleDESUtil.getJsonArrStr(SPUtils.getMySelf(SPUtils.MYFID),
								SPUtils.getMySelf(SPUtils.MYFRAD), jsonStr);
						if (TextUtils.isEmpty(json)) {
							if (handler != null)
								handler.obtainMessage(GET_MEMBERS_ERROR).sendToTarget();
						} else if (json.startsWith("{\"")) {
							if (handler != null)
								handler.obtainMessage(GET_MEMBERS_ERROR).sendToTarget();
						} else {
							JSONArray ja = JSONParser.getJSONArray(json);
							if (ja.length() == 0) {
								if (handler != null)
									handler.obtainMessage(GET_MEMBERS_ERROR).sendToTarget();
							} else {
								List<UserInfoEntity> members = new ArrayList<UserInfoEntity>();
								for (int i = 0; i < ja.length(); i++) {
									JSONObject jo = ja.getJSONObject(i);
									String uid = JSONParser.getString(jo, "uid");
									String name = JSONParser.getString(jo, "name");
									String phone = JSONParser.getString(jo, "phone");
									String role = JSONParser.getString(jo, "role");
									String urad = JSONParser.getString(jo, "urad");
									String avatar = JSONParser.getString(jo, "avatar");
									MemberInfoEntity memberInfo = new MemberInfoEntity(uid, urad, name, role, phone, avatar);
									UserInfoEntity userInfoEntity = new UserInfoEntity();
									userInfoEntity.setUid(phone);
									userInfoEntity.setNickname(name);
									userInfoEntity.setIcon(avatar);
									userInfoEntity.setRole(Integer.parseInt(role));
									userInfoEntity.setTelephone(phone);
									userInfoEntity.setFid(SPUtils.getMySelf(SPUtils.MYFID));
									members.add(userInfoEntity);
									MembersModel.insertMembers(context,	memberInfo);
								}
								FS.getInstance().mMemberAll = members;
								//								UserModel userModel = new UserModel(FS.getInstance());
								//								userModel.deleteUserInfoTable();
								//								userModel.insertMemberAll(FS.getInstance().mMemberAll);// 保存成员信息到数据库
								//								FS.getInstance().updateDBData();
								/* 代码逻辑与框架结构很重要 */
								//								MemberListUtils.getInstance()
								//								.setMembers(members);
								if (handler != null)
									handler.obtainMessage(GET_MEMBERS,	members).sendToTarget();
							}
						}
					} catch (Exception e) {
						L.e("maf", "error--", e);
					}

				}
			}
		});
	}

	public MemberInfoEntity getCurMemberURAD(Context context) {
		//		MembersModel model = new MembersModel();
		//		List<MemberInfoEntity> memberInfos = model.queryMembers(context);  // 将初始化对象改成一个调用静态方法
		List<MemberInfoEntity> memberInfos = MembersModel.queryMembers(context);
		if (memberInfos != null) {
			for (int i = 0; i < memberInfos.size(); i++) {
				MemberInfoEntity memberInfo = memberInfos.get(i);
				if (memberInfo.getPhone().equals(MemberListUtils.getInstance().getCurrentUser().getUid())) {
					return memberInfo;
				}
			}
		}
		return null;
	}
	
	public void getMembersUID2(final Context context) {
		HttpUtils.startHttpGet(URLUtils.URL_TASK_GET + getMembersQuertStr(),
				new HttpUtils.HttpResultCallback() {

			@Override
			public void result(String url, boolean isResult,
					String jsonStr) {
				if (isResult) {
					try {
						// String json = TripleDESUtil.getJsonArrStr(
						// SPUtils.getFID2(), SPUtils.getFRAD(),
						// jsonStr);
						String json = TripleDESUtil.getJsonArrStr(
								SPUtils.getMySelf(SPUtils.MYFID),
								SPUtils.getMySelf(SPUtils.MYFRAD), jsonStr);
						if (TextUtils.isEmpty(json)) {
							if (MainService.serviceHandler != null)
								MainService.serviceHandler.obtainMessage(GET_MEMBERS_ERROR).sendToTarget();
						} else if (json.startsWith("{\"")) {
							if (MainService.serviceHandler != null)
								MainService.serviceHandler.obtainMessage(GET_MEMBERS_ERROR).sendToTarget();
						} else {
							JSONArray ja = JSONParser.getJSONArray(json);
							if (ja.length() == 0) {
								if (MainService.serviceHandler != null)
									MainService.serviceHandler.obtainMessage(GET_MEMBERS_ERROR).sendToTarget();
							} else {
								// MembersModel.delMembersTab(context);
								List<UserInfoEntity> members = new ArrayList<UserInfoEntity>();
								for (int i = 0; i < ja.length(); i++) {
									JSONObject jo = ja.getJSONObject(i);
									String uid = JSONParser.getString(jo, "uid");
									String name = JSONParser.getString(jo, "name");
									String phone = JSONParser.getString(jo, "phone");
									String role = JSONParser.getString(jo, "role");
									String urad = JSONParser.getString(jo, "urad");
									String avatar = JSONParser.getString(jo, "avatar");
									MemberInfoEntity memberInfo = new MemberInfoEntity(uid, urad, name, role,phone, avatar);
									UserInfoEntity userInfoEntity = new UserInfoEntity();
									// userInfoEntity.setUid(uid);
									userInfoEntity.setUid(phone);
									userInfoEntity.setNickname(name);
									userInfoEntity.setIcon(avatar);
									userInfoEntity.setRole(Integer.parseInt(role));
									userInfoEntity.setTelephone(phone);
									userInfoEntity.setFid(SPUtils.getMySelf(SPUtils.MYFID));
									members.add(userInfoEntity);
									MembersModel.insertMembers(context,	memberInfo);
									// 异步下载图片
									if(!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(avatar)){
										IconImageUtils.getInstance().downIconImgIfNotExits(phone,avatar);
									}
//									if (!("").equals(phone)	&& !("").equals(avatar) 
//											&& phone != null && avatar != null) {
//										IconImageUtils.getInstance().downIconImgIfNotExits(phone,avatar);
//									}
								}
								FS.getInstance().mMemberAll = members;
								UserModel userModel = new UserModel(FS.getInstance());
								userModel.deleteUserInfoTable();
								userModel.insertMemberAll(FS.getInstance().mMemberAll);// 保存成员信息到数据库
								FS.getInstance().updateDBData();
								/* 代码逻辑与框架结构很重要 */
								MemberListUtils.getInstance().setMembers(members);
								if (MainService.serviceHandler != null)
									MainService.serviceHandler.obtainMessage(GET_MEMBERS, members).sendToTarget();
							}
						}
					} catch (Exception e) {
						L.e("maf", "error--", e);
					}

				}
			}
		});
	}
	public void initCurMember(){
		boolean hasBaby=false;
		if(FS.getInstance().self().getRole()!=2){
			for (UserInfoEntity u : members) {
				if (u.getRole() == 2) {
					hasBaby=true;
					setCurrentUser(u);
					break;
				}
			}
			if(!hasBaby){
				setCurrentUser(FS.getInstance().self());
			}
		}else{
			setCurrentUser(FS.getInstance().self());
		}
	}
}
